<template>
  <doc-alert title="【交易】交易订单" url="https://doc.iocoder.cn/mall/trade-order/" />
  <doc-alert title="【交易】购物车" url="https://doc.iocoder.cn/mall/trade-cart/" />

  <!-- 搜索 -->
  <ContentWrap>
    <el-form
      ref="queryFormRef"
      :inline="true"
      :model="queryParams"
      class="-mb-15px"
      label-width="68px"
    >
      <el-form-item
        label="手机号码"
        prop="userMobile"
      >
        <el-input
          v-model="queryParams.userMobile"
          class="!w-280px"
          clearable
          placeholder="请输入手机号码"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item
        label="商品信息"
        prop="spuInfo"
      >
        <el-input
          v-model="queryParams.spuInfo"
          class="!w-280px"
          clearable
          placeholder="请输入"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品类型" prop="productType">
        <el-select v-model="queryParams.productType" class="!w-280px" clearable placeholder="全部">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.TRADE_ORDER_PRODUCTTYPE_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon class="mr-5px" icon="ep:search" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon class="mr-5px" icon="ep:refresh" />
          重置
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" row-key="id">
      <OrderTableColumn :list="list" :pick-up-store-list="pickUpStoreList">
        <template #default="{ row }">
          <div class="flex items-center justify-center">
            <el-button
              v-hasPermi="['localLife:order:query']"
              link
              type="primary"
              @click="openDetail(row.id)"
            >
              <Icon icon="ep:notification" />
              详情
            </el-button>
            <el-dropdown
              v-hasPermi="['localLife:order:update']"
              @command="(command) => handleCommand(command, row)"
            >
              <el-button link type="primary">
                <Icon icon="ep:d-arrow-right" />
                更多
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item
                    v-if="
                      row.deliveryType === DeliveryTypeEnum.EXPRESS.type &&
                      row.status === TradeOrderStatusEnum.UNDELIVERED.status
                    "
                    command="delivery"
                  >
                    <Icon icon="ep:takeaway-box" />
                    发货
                  </el-dropdown-item>
                  <el-dropdown-item command="remark">
                    <Icon icon="ep:chat-line-square" />
                    备注
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </template>
      </OrderTableColumn>
    </el-table>
    <Pagination
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.pageNo"
      :total="total"
      @pagination="getList"
    />
  </ContentWrap>
</template>

<script lang="ts" setup>
import { ref, reactive, unref, watch, onMounted } from 'vue'
import type { FormInstance } from 'element-plus'
import * as TradeOrderApi from '@/api/mall/trade/order'
import * as PickUpStoreApi from '@/api/mall/trade/delivery/pickUpStore/index'
import * as DeliveryExpressApi from '@/api/mall/trade/delivery/express'
import { DICT_TYPE, getIntDictOptions, getStrDictOptions } from '@/utils/dict'
import { DeliveryTypeEnum, TradeOrderStatusEnum } from '@/utils/constants'
import { OrderTableColumn } from './components'
import { useRouter } from 'vue-router'

const { currentRoute, push } = useRouter()
const loading = ref(false)
const total = ref(0)
const list = ref<TradeOrderApi.OrderVO[]>([])
const queryFormRef = ref<FormInstance>()
const queryParams = ref({
  pageNo: 1,
  pageSize: 10,
  status: undefined,
  payChannelCode: undefined,
  createTime: undefined,
  terminal: undefined,
  type: undefined,
  deliveryType: undefined,
  logisticsId: undefined,
  pickUpStoreId: undefined,
  pickUpVerifyCode: undefined,
  productType: 'TIME_CARD'
})
const queryType = reactive({ queryParam: '' })
const dynamicSearchList = ref([
  { value: 'no', label: '订单号' },
  { value: 'userId', label: '用户UID' },
  { value: 'userNickname', label: '用户昵称' },
  { value: 'userMobile', label: '用户电话' }
])

const inputChangeSelect = (val: string) => {
  dynamicSearchList.value
    .filter((item) => item.value !== val)
    .forEach((item1) => {
      if (queryParams.value.hasOwnProperty(item1.value)) {
        delete queryParams.value[item1.value]
      }
    })
}

const getList = async () => {
  loading.value = true
  try {
    const data = await TradeOrderApi.getLocalOrderWriteoffPage(unref(queryParams))
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

const handleQuery = async () => {
  queryParams.value.pageNo = 1
  await getList()
}

const resetQuery = () => {
  queryFormRef.value?.resetFields()
  queryParams.value = {
    pageNo: 1,
    pageSize: 10,
    status: undefined,
    payChannelCode: undefined,
    createTime: undefined,
    terminal: undefined,
    type: undefined,
    deliveryType: undefined,
    logisticsId: undefined,
    pickUpStoreId: undefined,
    pickUpVerifyCode: undefined
  }
  handleQuery()
}

const openDetail = (id: number) => {
  push({ name: 'LocalLifeOrderDetail', params: { id } })
}

const deliveryFormRef = ref()
const updateRemarkForm = ref()
const handleCommand = (command: string, row: TradeOrderApi.OrderVO) => {
  switch (command) {
    case 'remark':
      updateRemarkForm.value?.open(row)
      break
    case 'delivery':
      deliveryFormRef.value?.open(row)
      break
  }
}

watch(
  () => currentRoute.value,
  () => {
    getList()
  }
)

const pickUpStoreList = ref<PickUpStoreApi.DeliveryPickUpStoreVO[]>([])
const deliveryExpressList = ref<DeliveryExpressApi.DeliveryExpressVO[]>([])

onMounted(async () => {
  await getList()
  if (PickUpStoreApi.getSimpleDeliveryPickUpStoreList) {
    pickUpStoreList.value = await PickUpStoreApi.getSimpleDeliveryPickUpStoreList()
  }
  if (DeliveryExpressApi.getSimpleDeliveryExpressList) {
    deliveryExpressList.value = await DeliveryExpressApi.getSimpleDeliveryExpressList()
  }
})
</script>
